#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include "data.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_ptcpsocket(new QTcpSocket)
{
    ui->setupUi(this);

    init_network();

    connect(ui->pushButton_send, &QPushButton::clicked, this, &Widget::sendbtn_clicked);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_network(){
    m_ptcpsocket->connectToHost("127.0.0.1", 8099);

    connect(m_ptcpsocket, &QTcpSocket::connected, this, &Widget::connect_ok);

    connect(m_ptcpsocket, &QTcpSocket::readyRead, this, &Widget::ready_read);
}

void Widget::connect_ok(){
    QMessageBox::information(this, "connect", "connect server success");

    return;
}

void Widget::sendbtn_clicked(){
    data_t dd;
    dd.a = ui->lineEdit_a->text().toUInt();
    dd.b = ui->lineEdit_b->text().toInt();

    QByteArray ba;
    QDataStream stream(&ba, QIODevice::WriteOnly);

    //序列化
    stream << dd.a << dd.b;
    m_ptcpsocket->write(ba);
    return;
}

void Widget::ready_read(){
    QByteArray ba = m_ptcpsocket->readAll();
    QDataStream stream(&ba, QIODevice::ReadOnly);
    data_t dd;

    //反序列化
    stream >> dd.a >> dd.b >> dd.ret;

    ui->lineEdit_res->setText(QString::number(dd.ret));

    return;
}

